<template>
  <div class="system-menu-dialog-container">
    <el-dialog
      :title="state.dialog.title"
      v-model="state.dialog.isShowDialog"
      width="769px"
    >
      <el-form
        ref="menuDialogFormRef"
        :rules="rules"
        :model="state.ruleForm"
        size="default"
        label-width="80px"
      >
        <el-row :gutter="35">
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
            <el-form-item label="上级菜单" prop="menuSuperior">
              <el-cascader
                :options="state.menuData"
                :props="{ checkStrictly: true, value: 'id', label: 'title' }"
                placeholder="请选择上级菜单"
                clearable
                class="w100"
                v-model="state.ruleForm.menuSuperior"
              >
                <template #default="{ node, data }">
                  <span>{{ data.title }}</span>
                  <span v-if="!node.isLeaf">
                    ({{ data.children.length }})
                  </span>
                </template>
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
            <el-form-item label="菜单类型" prop="menuType">
              <el-radio-group v-model="state.ruleForm.menuType">
                <el-radio label="menu">菜单</el-radio>
                <el-radio label="btn">按钮</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="菜单名称" prop="meta.title">
              <el-input
                v-model="state.ruleForm.meta.title"
                placeholder="格式：message.router.xxx"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <template v-if="state.ruleForm.menuType === 'menu'">
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
              <el-form-item label="路由名称" prop="name">
                <el-input
                  v-model="state.ruleForm.name"
                  placeholder="路由中的 name 值"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
              <el-form-item label="路由路径" prop="path">
                <el-input
                  v-model="state.ruleForm.path"
                  placeholder="路由中的 path 值"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
              <el-form-item label="重定向" prop="redirect">
                <el-input
                  v-model="state.ruleForm.redirect"
                  placeholder="请输入路由重定向"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
              <el-form-item label="菜单图标" prop="meta.icon">
                <IconSelector
                  placeholder="请输入菜单图标"
                  v-model="state.ruleForm.meta.icon"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
              <el-form-item  label="组件路径" prop="component">
                <el-input
                  v-model="state.ruleForm.component"
                  placeholder="组件路径"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
              <el-form-item label="链接地址" prop="meta.isLink">
                <el-input
                  v-model="state.ruleForm.meta.isLink"
                  placeholder="外链/内嵌时链接地址（http:xxx.com）"
                  clearable
                  :disabled="!state.ruleForm.isLink"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
              <el-form-item label="权限标识" prop="meta.roles">
                <el-select
                  v-model="state.ruleForm.meta.roles"
                  multiple
                  placeholder="取角色管理"
                  clearable
                  class="w100"
                >
                  <el-option v-for="(item,index) in  rolesOpitons" :key="index" :label="item.label" :value="item.value"></el-option>
                 
                </el-select>
              </el-form-item>
            </el-col>
          </template>
          <template v-if="state.ruleForm.menuType === 'btn'">
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
              <el-form-item label="权限标识" prop="btnPower">
                <el-input
                  v-model="state.ruleForm.btnPower"
                  placeholder="请输入权限标识"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
          </template>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="菜单排序" prop="menuSort">
              <el-input-number
                v-model="state.ruleForm.menuSort"
                controls-position="right"
                placeholder="请输入排序"
                class="w100"
              />
            </el-form-item>
          </el-col>
          <template v-if="state.ruleForm.menuType === 'menu'">
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
              <el-form-item label="是否隐藏" prop="meta.isHide">
                <el-radio-group v-model="state.ruleForm.meta.isHide">
                  <el-radio :label="true">隐藏</el-radio>
                  <el-radio :label="false">不隐藏</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
              <el-form-item label="页面缓存" prop="meta.isKeepAlive">
                <el-radio-group v-model="state.ruleForm.meta.isKeepAlive">
                  <el-radio :label="true">缓存</el-radio>
                  <el-radio :label="false">不缓存</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
              <el-form-item label="是否固定" prop="meta.isAffix">
                <el-radio-group v-model="state.ruleForm.meta.isAffix">
                  <el-radio :label="true">固定</el-radio>
                  <el-radio :label="false">不固定</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
              <el-form-item label="是否外链" prop="isLink">
                <el-radio-group
                  v-model="state.ruleForm.isLink"
                  :disabled="state.ruleForm.meta.isIframe"
                >
                  <el-radio :label="true">是</el-radio>
                  <el-radio :label="false">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
              <el-form-item label="是否内嵌" prop="meta.isIframe">
                <el-radio-group
                  v-model="state.ruleForm.meta.isIframe"
                  @change="onSelectIframeChange"
                >
                  <el-radio :label="true">是</el-radio>
                  <el-radio :label="false">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </template>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onCancel" size="default">取 消</el-button>
          <el-button type="primary" @click="onSubmit" size="default">{{
            state.dialog.submitTxt
          }}</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="systemMenuDialog">
import { inject } from "vue";
import { defineAsyncComponent, reactive, onMounted, ref ,nextTick } from "vue";
import { storeToRefs } from "pinia";
import { useRoutesList } from "/@/stores/routesList";
import { setBackEndControlRefreshRoutes } from "/@/router/backEnd";
import { AddOrUpdateMenu } from "../../../api/project";
import { initBackEndControlRoutes } from "/@/router/backEnd";
import { dataType } from "element-plus/es/components/table-v2/src/common";
import {GetRoles} from '../../../api/projectManage/projectList'
// 定义子组件向父组件传值/事件
const emit = defineEmits(["refresh"]);

const reload = inject("reload");
// 引入组件
const IconSelector = defineAsyncComponent(() =>
  import("/@/components/iconSelector/index.vue")
);

// 定义变量内容
const menuDialogFormRef = ref();
const stores = useRoutesList();
const { routesList } = storeToRefs(stores);
const state = reactive({
  // 参数请参考 `/src/router/route.ts` 中的 `dynamicRoutes` 路由菜单格式
  ruleForm: {
    menuSuperior: [], // 上级菜单
    menuType: "menu", // 菜单类型
    name: "", // 路由名称
    component: "", // 组件路径
    componentAlias: "", // 组件路径别名
    isLink: false, // 是否外链
    menuSort: 0, // 菜单排序
    path: "", // 路由路径
    redirect: "", // 路由重定向，有子集 children 时
    meta: {
      title: "", // 菜单名称
      icon: "", // 菜单图标
      isHide: false, // 是否隐藏
      isKeepAlive: false, // 是否缓存
      isAffix: false, // 是否固定
      isLink: "", // 外链/内嵌时链接地址（http:xxx.com），开启外链条件，`1、isLink: 链接地址不为空`
      isIframe: false, // 是否内嵌，开启条件，`1、isIframe:true 2、isLink：链接地址不为空`
      roles: "", // 权限标识，取角色管理
    },
    btnPower: "", // 菜单类型为按钮时，权限标识
  },
  menuData: [], // 上级菜单数据
  dialog: {
    isShowDialog: false,
    type: "",
    title: "",
    submitTxt: "",
  },
});

let rules = ref({
  menuSuperior: [
    { required: false, message: "请选择上级菜单", trigger: "change" },
  ],
  menuType: [{ required: false, message: "请输入菜单名称", trigger: "blur" }],
  name: [{ required: false, message: "请输入菜单路径", trigger: "blur" }],
  component: [{ required: false, message: "请输入菜单图标", trigger: "blur" }],
  isLink: [{ required: false, message: "请输入菜单图标", trigger: "blur" }],
  menuSort: [{ required: false, message: "请输入菜单图标", trigger: "blur" }],
  path: [{ required: false, message: "请输入菜单图标", trigger: "blur" }],
  redirect: [{ required: false, message: "请输入菜单图标", trigger: "blur" }],
  'meta.title': [{ required: false, message: "请输入菜单图标", trigger: "blur" }],

  'meta.icon': [{ required: false, message: "请输入菜单图标", trigger: "blur" }],
  'meta.isHide': [{ required: false, message: "请输入菜单图标", trigger: "blur" }],
  'meta.isKeepAlive': [
    { required: false, message: "请输入菜单图标", trigger: "blur" },
  ],
  'meta.isAffix': [{ required: false, message: "请输入菜单图标", trigger: "blur" }],
  

  'meta.isLink': [{ required: false, message: "请输入菜单图标", trigger: "blur" }],

  'meta.roles': [{ required: false, message: "请输入菜单图标", trigger: "blur" }],

  btnPower: [{ required: false, message: "请输入菜单图标", trigger: "blur" }],
  componentAlias: [
    { required: false, message: "请输入菜单图标", trigger: "blur" },
  ],
});

// 获取 pinia 中的路由
const getMenuData = (routes) => {
  const arr = [];
  routes.map((val) => {
    val["title"] = val.meta?.title;
    arr.push({ ...val });
    if (val.children) getMenuData(val.children);
  });
  return arr;
};
// 打开弹窗

let rowData = ref({});
let typeOpean = ref("");
const openDialog = (type, row) => {
  if (type === "edit") {
    typeOpean.value = "edit";
    // 模拟数据，实际请走接口
    row.menuType = "menu";
    

    rowData.value = JSON.parse(JSON.stringify(row));
    state.ruleForm = JSON.parse(JSON.stringify(row));
    state.ruleForm.menuSort = JSON.parse(JSON.stringify(row)).menuSort || 1;
    console.log(JSON.parse(JSON.stringify(row)))
	state.ruleForm.component = row.ComponentName
    state.ruleForm.meta.roles = JSON.parse(
      JSON.stringify(row)
    ).meta.roles.split(",");
    state.dialog.title = "修改菜单";
    state.dialog.submitTxt = "修 改";

    state.ruleForm.menuSuperior = deepChildren(rowData.value.id, state.menuData)

  } else {
    typeOpean.value = "add";
    state.dialog.title = "新增菜单";
    state.dialog.submitTxt = "新 增";
    // 清空表单，此项需加表单验证才能使用
    nextTick(() => {
    	menuDialogFormRef.value.resetFields();
    });
  }
  state.dialog.type = type;
  state.dialog.isShowDialog = true;
};

let deepChildren = (ids, data) => {
  let arr = [];

  data.forEach((v) => {

    if (v.id == ids || !v.children) {
      arr = [];
    } else {
      arr = deepFn(
        ids,
        state.menuData.filter((v) => v.children)
      );
    }
  });

 if(arr.includes('')){
	 arr = []
 }else{
	arr = arr.reduce((prev,next)=>{
		if(!prev.includes(next)){
			prev.push(next)
		}
		return prev
	},[])
	arr.reverse()
	arr.splice(arr.length-1,1)
 }
 
 return arr;
};

let deepFn = (id, data,parentId='') => {
	
    let idsArr = [];
    data.forEach((v) => {
      if (v.children) {
        let deepArrr = deepFn(id, v.children,v.id);
       
       
        if(deepArrr.length>0){
          idsArr = idsArr.concat(deepArrr,v.id);
          
        }
      } 
  
      if (v.id == id) {
          idsArr.push(v.id)
          idsArr.push(parentId)
         
        }
    });
 
    return idsArr;
  };

// 关闭弹窗
const closeDialog = () => {
  menuDialogFormRef.value.resetFields();
  state.dialog.isShowDialog = false;
};
// 是否内嵌下拉改变
const onSelectIframeChange = () => {
  if (state.ruleForm.meta.isIframe) state.ruleForm.isLink = true;
  else state.ruleForm.isLink = false;
};
// 取消
const onCancel = () => {
  closeDialog();
};
// 提交
const onSubmit = async () => {
  console.log(state.dialog.type);
  if (typeOpean.value === "add") {
    let obj = {
      parent_id:
        state.ruleForm.menuSuperior.length > 0
          ? state.ruleForm.menuSuperior[state.ruleForm.menuSuperior.length - 1]
          : "",
      menu_sort: state.ruleForm.menuSort,
      path: state.ruleForm.path,
      name: state.ruleForm.name,
      component: state.ruleForm.component,
      redirect: state.ruleForm.redirect,
      meta_title: state.ruleForm.meta.title,
      meta_isLink: state.ruleForm.meta.isLink,
      meta_isHide: state.ruleForm.meta.isHide,
      meta_isKeepAlive: state.ruleForm.meta.isKeepAlive,
      meta_isAffix: state.ruleForm.meta.isAffix,
      meta_isIframe: state.ruleForm.meta.isIframe,
      meta_roles: state.ruleForm.meta.roles,
      meta_icon: state.ruleForm.meta.icon,
    };
    !obj.parent_id ? delete obj.parent_id : "";
    obj.meta_roles = obj.meta_roles.join(",");

    await AddOrUpdateMenu(obj);
    closeDialog(); // 关闭弹窗
    menuDialogFormRef.value.resetFields();
    await initBackEndControlRoutes();
    state.menuData = getMenuData(routesList.value);
    emit("refresh", true);
  } else {
    
	let obj = {
		...state.ruleForm,
		parent_id:
        state.ruleForm.menuSuperior.length > 0
          ? state.ruleForm.menuSuperior[state.ruleForm.menuSuperior.length - 1]
          : "",
		  menu_sort: state.ruleForm.menuSort,
      path: state.ruleForm.path,
      name: state.ruleForm.name,
      component: state.ruleForm.component,
      redirect: state.ruleForm.redirect,
      meta_title: state.ruleForm.meta.title,
      meta_isLink: state.ruleForm.meta.isLink,
      meta_isHide: state.ruleForm.meta.isHide,
      meta_isKeepAlive: state.ruleForm.meta.isKeepAlive,
      meta_isAffix: state.ruleForm.meta.isAffix,
      meta_isIframe: state.ruleForm.meta.isIframe,
      meta_roles: state.ruleForm.meta.roles,
      meta_icon: state.ruleForm.meta.icon,
	}
	!obj.parent_id ? delete obj.parent_id : "";
	
    obj.meta_roles = obj.meta_roles.join(",");
	await AddOrUpdateMenu(obj);
    closeDialog(); // 关闭弹窗
    menuDialogFormRef.value.resetFields();
    await initBackEndControlRoutes();
    state.menuData = getMenuData(routesList.value);
    emit("refresh", true);

  }
 
};
// 页面加载时

let rolesOpitons = ref([])
onMounted(async() => {
 let res = await GetRoles()
 rolesOpitons.value = res.map(v=>{
  return {
    label:v.role_name,
    value:v.role_name
  }
 })
  state.menuData = getMenuData(routesList.value);
});

// 暴露变量
defineExpose({
  openDialog,
});
</script>
